package com.ruoyi.file.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;

/**
 * MD5加密工具类.
 *
 * @version 2023/11/09
 * @since jdk1.8.0_144
 */
@Slf4j
public class Md5Utils {
    /**
     * 用来将字节转换成 16 进制表示的字符.
     */
    private static final char HEX_DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    /**
     *
     * @param b the byte array.
     * @return a hex string representation of the byte array.
     */
    private static String toHexString(byte[] b) {
        StringBuilder sb = new StringBuilder(b.length * 2);
        for (int i = 0; i < b.length; i++) {
            sb.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]);
            sb.append(HEX_DIGITS[b[i] & 0x0f]);
        }
        return sb.toString();
    }

    /**
     * MD5加密.
     * @param astr the source string.
     * @return MD5 string.
     * @throws Exception
     */
    public static String md5(String astr) {
        String md5 = null;
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(astr.getBytes());
            byte messageDigest[] = digest.digest();
            md5 = toHexString(messageDigest);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return md5;
    }

    /**
     * MD5加密.
     * @param filePath the source string.
     * @return MD5 string.
     * @throws Exception if any exceptions happened throw them.
     */
    public static String getFileMD5(String filePath) {
        try {
            FileInputStream inputStream = new FileInputStream(filePath);
            return getFileMD5(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * get file md5 and close the inputstream
     * .
     * @param inputStream the file input stream.
     * @return file md5 string.
     * @throws Exception if any exceptions happened throw them.
     */
    public static String getFileMD5(InputStream inputStream) {
        try {
            String md5 = DigestUtils.md5Hex(inputStream);
            inputStream.close();
            return md5;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
